<template>
  <div class="container">
    <!-- 头部 -->
    <div id="header">
      <div class="left">
        <div class="sort">
          <div
            :class="[{ selected: sort_type == 1 }]"
            @click="changeSortType(1)"
          >
            商品分拣
          </div>
          <div
            :class="[{ selected: sort_type == 2 }]"
            @click="changeSortType(2)"
          >
            用户分拣
          </div>
        </div>
        <div>
          <el-form class="header_form" ref="form" :inline="true" :model="form">
            <el-form-item label="" class="time">
              <el-date-picker
                @change="changeDatePick(1)"
                value-format="yyyy-MM-dd"
                v-model.trim="time"
                type="date"
                placeholder="选择配送日期"
                :clearable="false"
                class="send_date"
                :popper-append-to-body="false"
              >
              </el-date-picker>
            </el-form-item>

            <el-form-item label="" class="send_time">
              <el-select
                placeholder="请选择配送时间"
                @change="changeDatePick(2)"
                v-model="send_time_list"
              >
                <el-option label="全部" value=""></el-option>
                <el-option
                  v-for="(item, index) in SEARCH_DATA.send_time_list"
                  :key="index"
                  :label="item.times"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="">
              <el-select
                v-model="quick_select_type"
                class="label"
                placeholder="请选择"
                :popper-append-to-body="false"
                @change="changeQuickSelectType"
              >
                <el-option label="商品" value="1"></el-option>
                <el-option label="用户" value="2"></el-option>
              </el-select>

              <el-autocomplete
                class="inline-input"
                v-model.trim="state1"
                :trigger-on-focus="false"
                :fetch-suggestions="
                  (queryString, cb) => {
                    basicquerySearchAsync(queryString, cb);
                  }
                "
                :placeholder="quick_select_placeholder"
                @select="handleSelect"
                value-key="name"
                clearable
                @clear="handleClear"
              >
                <template slot-scope="{ item }">
                  {{ item.name }}
                </template></el-autocomplete
              >
            </el-form-item>
          </el-form>
        </div>
        <div class="more">
          <img src="@/assets/images/more.png" alt="" @click="moreSearch" />
          <span>更多</span>
        </div>

        <div class="sort_ject" v-if="work_show">
          <div>分工方式：{{ work_type[work_ids] }}</div>
          <div style="display: flex">
            <div>分拣任务：</div>
            <div>
              <el-popover placement="bottom-start" width="240" trigger="hover">
                <div style="display: flex; flex-wrap: wrap">
                  <div
                    class="user_tag"
                    v-for="(it, its) in sort_work"
                    :key="its"
                  >
                    {{ it }}
                  </div>
                </div>
                <div slot="reference">
                  <div class="over_hidden">
                    <div
                      style="margin-right: 0.1rem"
                      v-for="(it, its) in sort_work"
                      :key="its"
                    >
                      {{ it }}
                    </div>
                  </div>
                </div>
              </el-popover>
            </div>
          </div>
        </div>
      </div>

      <div class="right">
        <div class="set_quit">
          <div class="set_box">
            <div class="set" @click="show = !show">
              <img src="@/assets/images/set.png" alt="" />
              <span>设置</span>
            </div>
            <!-- -->
            <transition name="fade">
              <div class="operation clearfix" v-if="show">
                <div class="top">
                  <li>
                    <span>生产日期</span>
                    <el-switch
                      v-model="setting_data.data_manufacture"
                      @change="to_setting('data_manufacture')"
                      active-color="#4FA388"
                      inactive-color="#E9E9EB"
                    >
                    </el-switch>
                  </li>
                  <li>
                    <span>自动打印</span>
                    <el-switch
                      v-model="setting_data.auto_printing"
                      @change="to_setting('auto_printing')"
                      active-color="#4FA388"
                      inactive-color="#E9E9EB"
                    >
                    </el-switch>
                  </li>
                  <li>
                    <span>未分拣打印</span>
                    <el-switch
                      v-model="setting_data.no_sort_printing"
                      @change="to_setting('no_sort_printing')"
                      active-color="#4FA388"
                      inactive-color="#E9E9EB"
                    >
                    </el-switch>
                  </li>

                  <li>
                    <span>中崎智能称</span>
                    <el-switch
                      v-model="setting_data.switch"
                      @change="to_setting('switch')"
                      active-color="#4FA388"
                      inactive-color="#E9E9EB"
                    >
                    </el-switch>
                  </li>
                  <li>
                    <span>基础单位分拣</span>
                    <el-switch
                      v-model="setting_data.sorting_unit"
                      @change="setSortingunit"
                      active-color="#157455"
                      inactive-color="#E9E9EB"
                    >
                    </el-switch>
                  </li>
                  <li>
                    <span>显示</span>
                    <el-radio-group
                      @change="to_setting('is_show_several')"
                      v-model="setting_data.is_show_several"
                    >
                      <el-radio-button label="0">双列</el-radio-button>
                      <el-radio-button label="1">三列</el-radio-button>
                    </el-radio-group>
                  </li>
                  <!-- <li>
                    <span>临时编码</span>
                    <el-switch
                      v-model="setting_data.temporary_code"
                      active-color="#4FA388"
                      inactive-color="#E9E9EB"
                    >
                    </el-switch>
                  </li> -->
                </div>
                <div class="bottom">
                  <li @click="jump(1)">使用手册</li>
                  <li @click="jump(2)">常见问题</li>
                </div>
              </div>
            </transition>
          </div>

          <div class="quit">
            <img src="@/assets/images/quit.png" alt="" @click="handleLoout" />
            <span>退出</span>
          </div>
        </div>
      </div>
    </div>

    <div
      id="main_container"
      v-loading="loading"
      :element-loading-text="loading_text"
    >
      <!-- 最左侧用户单独区域 -->
      <div id="user" v-if="sort_type == 2" ref="left_user_percent">
        <div v-if="user_rank.length > 0">
          <div
            v-for="(item, index) in user_rank"
            :key="index"
            :class="[{ selected: user_rank_selected == item.code }, 'item']"
            @click="changeUser(item)"
          >
            <div class="top">
              <h3 class="h3span">{{ item.user_name }}</h3>
              <!-- <div class="top-total">总数: {{ item.total_sort_num }}</div> -->
            </div>
            <div class="bottom">
              <div class="left">
                <div
                  :style="{ width: item.sort_speed + '%' }"
                  class="percent"
                ></div>
              </div>
              <!-- <div class="right">{{ item.sort_speed }}%</div> -->
            </div>
            <div class="numBox">
              <span class="items"
                >总数:
                <span style="color: #b7630a">{{
                  item.total_sort_num
                }}</span></span
              >
              <span class="items" style="text-align: center"
                >已分捡:
                <span style="color: #4fa388">{{
                  item.sort_num | toFixed2
                }}</span></span
              >
              <span class="items" style="text-align: right"
                >未分拣:
                <span style="color: red">{{ item.no_sort_num }}</span></span
              >
            </div>
          </div>
        </div>
        <div class="no_data" v-else>
          <div>
            <i class="el-icon-warning-outline"></i>
            <p>暂无数据</p>
          </div>
        </div>
        <div class="left_fixed">
          <div class="left_fixed_item" @click="handleUp(1)">
            <img src="@/assets/images/up.png" alt="" />
          </div>
          <div class="left_fixed_item" @click="handleDown(1)">
            <img src="@/assets/images/down.png" alt="" />
          </div>
        </div>
      </div>
      <!-- 最左侧商品单独区域 -->
      <div id="goods" v-if="sort_type == 1" ref="left_goods_percent">
        <div v-if="goods_rank.length > 0">
          <div
            :class="['item', { selected: goods_rank_selected == item.id }]"
            v-for="item in goods_rank"
            :key="item.id"
            @click="changeGoods(item)"
          >
            <div class="top">
              <h3 class="h3span">{{ item.name }}</h3>
              <!-- <div class="top-total">总数: {{ item.total_sort_num }}</div> -->
            </div>
            <div class="bottom">
              <div class="left">
                <div
                  :style="{ width: item.sort_speed + '%' }"
                  class="percent"
                ></div>
              </div>
              <!-- <div class="right">{{ item.sort_speed }}%</div> -->
            </div>
            <div class="numBox">
              <span class="items"
                >总数:
                <span style="color: #b7630a">{{
                  item.total_sort_num
                }}</span></span
              >
              <span class="items" style="text-align: center"
                >已分捡:
                <span style="color: #4fa388">{{
                  item.sort_num | toFixed2
                }}</span></span
              >
              <span class="items" style="text-align: right"
                >未分拣:
                <span style="color: red">{{
                  calculation(item.total_sort_num, item.sort_num)
                }}</span></span
              >
            </div>
          </div>
        </div>
        <div class="no_data" v-else>
          <div>
            <i class="el-icon-warning-outline"></i>
            <p>暂无数据</p>
          </div>
        </div>
        <div class="left_fixed">
          <div class="left_fixed_item" @click="handleUp(3)">
            <img src="@/assets/images/up.png" alt="" />
          </div>
          <div class="left_fixed_item" @click="handleDown(3)">
            <img src="@/assets/images/down.png" alt="" />
          </div>
        </div>
      </div>
      <!-- 键盘区域--开始 -->
      <div class="summation">
        <div class="top">
          <li>
            <p style="width: 30%">
              用户名称
              <el-popover
                v-show="CURRENT_SORT_DATA.labels.length > 0"
                placement="bottom-start"
                width="240"
                trigger="click"
              >
                <div class="user_tag_box">
                  <div
                    class="user_tag"
                    v-for="item in CURRENT_SORT_DATA.labels"
                    :key="item"
                  >
                    {{ labels[item] }}
                  </div>
                </div>
                <img slot="reference" src="@/assets/images/label.png" alt="" />
              </el-popover>
            </p>

            <div style="overflow: hidden">
              {{ CURRENT_SORT_DATA.newname }}
            </div>
          </li>
          <li>
            <p style="width: 30%">商品名称</p>
            <div style="overflow: hidden">{{ CURRENT_SORT_DATA.name }}</div>
          </li>
          <li v-if="setting_data.data_manufacture">
            <p style="width: 30%">生产日期</p>
            <div style="overflow: hidden" class="production_date">
              <el-date-picker
                v-model="CURRENT_SORT_DATA.mfg"
                type="date"
                placeholder="选择时间"
                @change="add_production_time"
                value-format="yyyy-MM-dd"
                :disabled="CURRENT_SORT_DATA.status == 1"
              >
              </el-date-picker>
            </div>
          </li>

          <li>
            <p style="width: 30%">下单数量</p>
            <div style="overflow: hidden">
              {{
                CURRENT_SORT_DATA.base_order_num
                  ? CURRENT_SORT_DATA.base_order_num
                  : CURRENT_SORT_DATA.order_num + " " + CURRENT_SORT_DATA.unit
              }}
            </div>
          </li>
          <li>
            <p style="width: 30%">分拣数量</p>
            <div class="order_nums" v-if="!CURRENT_SORT_DATA.unit_list">
              <el-input
                ref="order_num_input"
                v-model.trim="CURRENT_SORT_DATA.new_sort_num"
                :placeholder="CURRENT_SORT_DATA.sort_num"
                @keyup.enter.native="add_sort_num"
                :disabled="CURRENT_SORT_DATA.status == 1"
              >
              </el-input>
              <p>{{ this.CURRENT_SORT_DATA.unit || "" }}</p>
            </div>
            <div class="order_num" v-else>
              <el-input
                ref="order_num_input"
                v-model.trim="CURRENT_SORT_DATA.new_sort_num"
                :placeholder="CURRENT_SORT_DATA.sort_num"
                @keyup.enter.native="add_sort_num"
                :disabled="CURRENT_SORT_DATA.status == 1"
              >
                <el-select
                  v-model="sortingUnit"
                  slot="append"
                  placeholder="请选择"
                  :disabled="CURRENT_SORT_DATA.status == 1"
                >
                  <el-option
                    v-for="item in CURRENT_SORT_DATA.unit_list"
                    :key="item.key"
                    :label="item.unit"
                    :value="item.key"
                  ></el-option>
                </el-select>
              </el-input>
            </div>
          </li>
          <li class="remark_li">
            <p style="width: 30%">用户备注</p>
            <div style="overflow: hidden" class="reamrk">
              {{ CURRENT_SORT_DATA.remark }}
            </div>
          </li>

          <li class="remark_li">
            <p style="width: 30%">订单备注</p>
            <div style="overflow: hidden" class="reamrk">
              {{
                CURRENT_SORT_DATA.order ? CURRENT_SORT_DATA.order.remark : ""
              }}
            </div>
          </li>
        </div>
        <div class="summation_keybord">
          <div class="number">
            <div
              class="item no_select"
              v-for="item in 9"
              :key="item"
              @click="handleNumber(item)"
            >
              {{ item }}
            </div>
            <div class="item no_select" @click="handleNumber(0)">0</div>
            <div class="item clear no_select" @click="handleNumber('.')">.</div>
            <div class="item no_select" @click="handleRemove()">
              <img src="@/assets/images/delete.png" alt="" />
            </div>
            <div class="item brown no_select" v-repeatClick @click="go_print">
              打印
            </div>
            <div class="item brown no_select" v-repeatClick @click="go_add">
              累加
            </div>
            <div class="item brown no_select" v-repeatClick @click="go_lack">
              缺货
            </div>
          </div>
          <div class="long no_select" v-repeatClick @click="add_sort_num">
            保存分拣
          </div>
          <div class="long red no_select" v-repeatClick @click="go_revoke">
            撤销
          </div>
        </div>
      </div>
      <!-- 键盘区域--结束 -->
      <!-- 商品区域--开始 -->
      <div class="goods" ref="container">
        <div>
          <div class="goods_header">
            <div
              class="item revoke no_select"
              v-repeatClick
              @click="go_lack_all"
            >
              撤销全部
            </div>
            <div
              class="item print no_select"
              v-repeatClick
              @click="go_print_all"
            >
              打印全部
            </div>
            <div class="item sort no_select" v-repeatClick @click="go_sort_all">
              分拣全部
            </div>
            <div class="item_right" v-if="false">
              <div class="sort_item no_sort">未分拣</div>
              <div class="sort_item is_sort">已分拣</div>
            </div>
          </div>
          <div class="goods_main" v-if="SORT_LIST.length > 0">
            <div
              @click="nextGoods(item, index)"
              v-for="(item, index) in SORT_LIST"
              :key="index"
            >
              <div
                :class="[
                  { selected: CURRENT_SELECTED == index },
                  [
                    sort_type == 1
                      ? setting_data.is_show_several == 1
                        ? 'item_goods'
                        : 'item_goodsMAX'
                      : setting_data.is_show_several == 1
                      ? 'item_user'
                      : 'item_userMAX',
                  ],
                  'no_sort',
                ]"
                v-if="item.status == 0"
              >
                <h3>{{ item.name }}</h3>
                <div>
                  <span>{{
                    item.base_order_num
                      ? item.base_order_num
                      : item.order_num + item.unit
                  }}</span>
                </div>
                <div v-show="sort_type == 1" class="name">
                  {{ item.newname }}
                </div>
              </div>

              <div
                :class="[
                  { selected: CURRENT_SELECTED == index },
                  { is_sort_selected: CURRENT_SELECTED == index },
                  [
                    sort_type == 1
                      ? setting_data.is_show_several == 1
                        ? 'item_goods'
                        : 'item_goodsMAX'
                      : setting_data.is_show_several == 1
                      ? 'item_user'
                      : 'item_userMAX',
                  ],
                  'is_sort',
                ]"
                v-if="item.status == 1"
              >
                <div class="tips">
                  <div
                    v-if="item.out_status == 1"
                    :class="[{ que: item.out_status == 1 }, 'dot']"
                  >
                    缺
                  </div>
                  <div
                    v-if="item.modify == 1"
                    :class="[{ geng: item.modify == 1 }, 'dot']"
                  >
                    更
                  </div>
                </div>
                <h3>{{ item.name }}</h3>
                <div v-if="item.base_order_num">
                  <span>{{ item.base_order_num }}</span>
                  <span>{{ item.sort_num }}{{ item.unit }}</span>
                </div>
                <div v-else>
                  <span>{{ item.order_num }}{{ item.unit }}</span>
                  <span>{{ item.sort_num }}{{ item.unit }}</span>
                </div>
                <div v-show="sort_type == 1" class="name">
                  {{ item.newname }}
                </div>
              </div>
            </div>
          </div>
          <div class="no_data no_data_main" v-else>
            <div>
              <i class="el-icon-warning-outline"></i>
              <p>暂无数据</p>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="page_container" v-if="false">
          <el-pagination
            :current-page.sync="currentPage3"
            :page-size="50"
            layout="prev, pager, next"
            :total="10000"
          >
          </el-pagination>
        </div>
        <div class="left_fixed">
          <div class="item no_select" @click="handleRefresh">
            <img src="@/assets/images/refresh.png" alt="" />
          </div>
          <div class="item no_select" @click="handleScreen">
            <img src="@/assets/images/screen.png" alt="" />
          </div>
          <div class="item no_select" @click="handleUp(2)">
            <img src="@/assets/images/up.png" alt="" />
          </div>
          <div class="item no_select" @click="handleDown(2)">
            <img src="@/assets/images/down.png" alt="" />
          </div>
        </div>
      </div>
      <!-- 商品区域--结束 -->
      <!-- 更多搜索 -->
      <div id="dialog" v-show="dialogShow">
        <goods
          :sortject="setting"
          v-show="sort_type == 1"
          @back="moreSearch"
          :SEARCH_DATA="SEARCH_DATA"
          @getGoodsData="getGoodsData"
          ref="child_goods"
        ></goods>

        <user
          v-show="sort_type == 2"
          @back="moreSearch"
          :SEARCH_DATA="SEARCH_DATA"
          @getUsersData="getUsersData"
          :sortject="setting"
          ref="child_user"
        ></user>
      </div>
    </div>

    <el-dialog
      title="累加分拣"
      :visible.sync="addDialogFormVisible"
      width="700px"
    >
      <el-form
        :model="form"
        class="add_dialog_form"
        label-width="160px"
        @submit.native.prevent
      >
        <el-form-item label="下单数量:" label-width="120px" class="addfenjian">
          <span class="add_num">{{ addInfo.order_num }}</span>
        </el-form-item>
        <el-form-item
          label="已分拣数量:"
          label-width="120px"
          class="addfenjian"
        >
          <span class="add_num">{{ addInfo.sort_num }}</span>
        </el-form-item>
        <el-form-item label="分拣数量:" label-width="120px" class="addfenjian">
          <el-input
            v-model.trim="addInfo.new_num"
            autocomplete="off"
            placeholder="智能称或输入数量后回车"
            size="medium"
            autofocus="true"
            type="number"
            ref="addInfoInput"
            @keyup.enter.native="countadd(1)"
            class="wid300"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否分次打印:" label-width="120px">
          <el-tooltip
            class="item"
            effect="dark"
            content="勾选后，每次累加数量都会打印标签"
            placement="top"
          >
            <i class="el-icon-question icon" style="padding-rigth: 30px"></i>
          </el-tooltip>
          <el-switch
            v-model="isPrint"
            active-color="#03A98E"
            class="mainor_switch"
            style="margin-left: 20px"
          ></el-switch>
        </el-form-item>
        <el-form-item label="累加明细:" label-width="120px">
          <el-tag
            size="mini"
            v-for="(item, index) in addInfo.numhistory"
            :key="index"
            style="margin-right: 6px"
            >{{ item }}</el-tag
          >
        </el-form-item>
        <el-form-item
          label="本次分拣数量:"
          label-width="120px"
          class="addfenjian"
        >
          <span class="add_num">{{ addInfo.add_sum }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="close">完 成</el-button>
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 打印子组件 -->
    <sort-note-print
      ref="printTemplate"
      v-show="false"
      id="printname"
    ></sort-note-print>
  </div>
</template>

<script>
import { apiUrl, objKeySort, Md5 } from "@/utils/public";

import {
  parseTime,
  handleScrollup,
  handleScrolldown,
  handleAllscreen,
  handleOutFullCreeen,
} from "@/utils/index";

import { removeToken } from "@/utils/auth";

import { logout } from "@/api/login";

import {
  to_setting,
  get_goods_type,
  get_goods_list,
  get_user_list,
  revoke,
  stock,
  revoke_list,
  sort_list,
  add_sort_num,
  add_production_time,
  get_find_user,
  get_goods_select,
  sort_num_accumulation,
} from "@/api/index";
import User from "@/views/search/user";
import Goods from "@/views/search/goods";
import SortNotePrint from "@/views/sort/sortPrintNote.vue";
import { mapGetters, mapMutations } from "vuex";
import ws from "@/utils/ZQEBSDK";

let init = new ws.initAPI();
let print = new ws.printAPI(init);

export default {
  computed: {
    ...mapGetters(["setting"]),
  },
  components: {
    User,
    Goods,
    SortNotePrint,
  },
  watch: {
    time: {
      handler(val) {
        this.SEARCH_DATA.time = val;
      },
      deep: true,
      immediate: true,
    },
  },
  data() {
    return {
      sortingUnit: 0, // 分拣单位 0基础1不是基础
      parseTime,
      handleScrollup,
      handleScrolldown,
      form: {
        name: "",
      },
      state1: "",
      restaurants: [],

      input3: "",
      input: "",
      show: false,
      value: "",
      timer: "",
      isScreen: false,
      isSys: true,
      // 是否分次打印
      isPrint: false,
      // 累加操作的信息

      addInfo: {
        id: "",
        num: "", //原始数据
        numhistory: [], //添加的记录
        new_num: "", //添加数据
        order_num: "", //下单数量
        sort_num: "0", //分拣数量
        add_sum: 0, //本次分拣的和
      },
      addDialogFormVisible: false,
      loading: false,
      loading_text: "拼命加载中...",
      // 快捷搜索
      quick_select_type: "1",
      quick_select_placeholder: "商品/助记码/编码",
      // 设置
      setting_data: {
        auto_printing: false,
        data_manufacture: false,
        no_sort_printing: false,
        sorting_unit: false,
        temporary_code: false,
        switch: false,
        is_show_several: 0,
      },
      // 分拣类型
      sort_type: 1, //1 :goods 2:user
      // 更多搜索弹窗
      dialogShow: false,
      //商品分类的类型选择
      SEARCH_DATA: {
        goods_type: [],
        group: [],
        send_time_list: [],
        line: [],
        time: "",
      },
      /* 搜索--开始 */
      time: parseTime(new Date(), "{y}-{m}-{d}"),
      sort_status: "",
      line_ids: "",
      goods_spu_ids: "",
      is_standard: "",
      pid: "",
      cid: "",
      group_id: "",
      uids: "",
      modify: "",
      out_status: "",
      send_time_list: "",
      remark: "",
      page: "1",
      pagesize: "100000",
      user_line_ids: "",
      user_group_id: "",
      user_uids: "",
      user_goods_spu_ids: "",
      /* 搜索--结束 */
      // 分拣数据列表 分拣
      SORT_LIST: [],
      // 当前分拣的数据
      CURRENT_SELECTED: 0,
      CURRENT_SORT_DATA: {
        member: {
          nickname: "......",
        },
        newname: "......",
        name: "......",
        order_num: "......",
        unit: "......",
        remark: "......",
        labels: [],
        status: "",
      },
      // 当前分拣用户的进度
      current_user_percent: {
        all: 0,
        is_sort: 0,
        no_sort: 0,
        percent: 0,
      },
      // 当前分拣的生产日期
      CURRENT_DATE: parseTime(new Date(), "{y}-{m}-{d}"),
      // 用户分拣百分比
      user_rank: [],
      user_rank_selected: 0,
      // 当前选中用户
      uid_zid: "",
      // 当前选中的商品
      goods_id_speed: "",
      // 用户的全部数据
      user_all_data: [],
      // 商品rank
      goods_rank: [],
      goods_rank_selected: 0,

      // 分页
      currentPage3: 5,
      // 用户标签
      labels: {},
      work_type: "",
      seting_name: {},
      sort_work: [],
      work_ids: "",
      work_show: false,
      worktype_show: false,
      switch_status: 0,
      _beforeUnload_time: "",
      _gap_time: "",
    };
  },
  filters: {
    toFixed2(num) {
      return Number(num).toFixed(2);
    },
  },
  methods: {
    ...mapMutations(["SET_SETTING"]),
    calculation(total_sort_num, sort_num) {
      let sum = (Number(total_sort_num) - Number(sort_num)).toFixed(2);
      if (!sum) {
        sum = 0;
      }
      return sum <= 0 ? 0 : sum;
    },
    // 刷新
    handleRefresh() {
      let type = this.sort_type;
      this.loading = true;
      switch (type) {
        case 1:
          this.get_goods_list();
          break;
        case 2:
          this.get_user_list();
          break;
      }
    },
    // 向上移动
    handleUp(type) {
      let el = "";
      switch (type) {
        case 1:
          el = this.$refs.left_user_percent;
          break;
        case 2:
          el = this.$refs.container;
          break;
        case 3:
          el = this.$refs.left_goods_percent;
          break;
      }
      this.handleScrollup(el);
    },
    // 向下移动
    handleDown(type) {
      let el = "";
      switch (type) {
        case 1:
          el = this.$refs.left_user_percent;
          break;
        case 2:
          el = this.$refs.container;
          break;
        case 3:
          el = this.$refs.left_goods_percent;
          break;
      }
      this.handleScrolldown(el);
    },
    handleScreen() {
      if (!this.isScreen) {
        this.screen();
        this.isScreen = true;
      } else {
        this.outFullCreeen();
        this.isScreen = false;
      }
    },
    // 全屏
    screen() {
      handleAllscreen();
    },
    outFullCreeen() {
      handleOutFullCreeen();
    },
    // 退出登录
    handleLoout() {
      this.$confirm("此操作将退出登录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "quit_message",
      })
        .then(() => {
          if (this.setting.switch == 1) {
            print.webSocketClose();
          }
          let data = Object.assign(
            {
              sign: Md5(
                objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
              ),
            },
            apiUrl().name
          );
          logout(data).then((res) => {
            if (res.errcode == 0) {
              removeToken();
              this.$router.push(`/login?redirect=${this.$route.fullPath}`);
            }
          });
        })
        .catch(() => {});
    },
    // 设置
    to_setting(type) {
      let data;
      if (type == "is_show_several") {
        data = Object.assign(
          {
            sign: Md5(
              objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
            ),
          },
          apiUrl().name,
          { [type]: this.setting_data[type] == 0 ? 1 : 2 }
        );
      } else {
        data = Object.assign(
          {
            sign: Md5(
              objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
            ),
          },
          apiUrl().name,
          { [type]: this.setting_data[type] ? 2 : 1 }
        );
      }

      to_setting(data).then((res) => {
        if (res.errcode == 0) {
          this.SET_SETTING(res.data);
          this.$message.success("设置成功");
          if (this.setting.switch == 1 && type == "switch") {
            this.switch_change();
          } else if (this.setting.switch == 0 && type == "switch") {
            print.webSocketClose();
          }
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 帮助中心&&使用手册跳转
    jump(type) {
      let path = "";
      switch (type) {
        case 1:
          path = "document";
          break;
        case 2:
          path = "question";
          break;
      }
      this.$router.push({
        path: path,
      });
    },
    // 更多搜索
    moreSearch() {
      this.dialogShow = !this.dialogShow;
    },
    // 商品分拣 用户分拣选择
    changeSortType(type) {
      // type  1  商品分拣  type  2 用户分拣
      this.CURRENT_SORT_DATA = {
        member: {
          nickname: "......",
        },
        newname: "......",
        name: "......",
        order_num: "......",
        unit: "......",
        remark: "......",
        labels: [],
      };
      this.CURRENT_SELECTED = 0;
      this.SORT_LIST = [];
      this.quick_select_type = "1";
      this.user_goods_spu_ids = "";
      this.user_uids = "";
      this.uids = "";
      this.goods_spu_ids = "";
      this.state1 = "";
      this.pid = "";
      this.cid = "";
      this.loading = true;
      this.uid_zid = "";
      this.goods_id_speed = "";
      switch (type) {
        case 1:
          this.goods_rank_selected = "";
          this.get_goods_list();
          this.$refs.child_goods.updata();
          this.$refs.child_goods.get_goods_select();
          this.$refs.child_goods.get_find_user();
          break;
        case 2:
          this.get_user_list();
          this.$refs.child_user.updata();
          this.$refs.child_user.get_goods_select();
          this.$refs.child_user.get_find_user();
          break;
      }
      this.sort_type = type;
    },
    // 商品子组件  获取数据
    getGoodsData(value) {
      let data = value;
      this.cid = data.cid;
      this.goods_spu_ids = data.goods_spu_ids;
      this.group_id = data.group_id;
      this.is_standard = data.is_standard;
      this.line_ids = data.line_ids;
      this.modify = data.modify;
      this.out_status = data.out_status;
      this.pid = data.pid;
      this.remark = data.remark;
      this.uids = data.uids;
      this.goods_rank_selected = "";
      if (this.goods_spu_ids) {
        this.goods_id_speed = "";
      }
      this.$nextTick(() => {
        this.loading = true;
        this.CURRENT_SORT_DATA = {
          member: {
            nickname: "......",
          },
          newname: "......",
          name: "......",
          order_num: "......",
          unit: "......",
          remark: "......",
          labels: [],
        };
        this.get_goods_list();
      });
    },

    // 用户组件  获取数据
    getUsersData(value) {
      let data = value;
      this.user_uids = data.uids;
      this.user_group_id = data.group_id;
      this.user_line_ids = data.line_ids;
      this.user_goods_spu_ids = data.goods_spu_ids;
      if (this.user_uids) {
        this.uid_zid = "";
      }
      this.$nextTick(() => {
        this.loading = true;
        this.CURRENT_SORT_DATA = {
          member: {
            nickname: "......",
          },
          newname: "......",
          name: "......",
          order_num: "......",
          unit: "......",
          remark: "......",
          labels: [],
        };
        this.get_user_list();
      });
    },
    // 商品分拣加载
    get_goods_list() {
      this.CURRENT_SORT_DATA = {
        member: {
          nickname: "......",
        },
        newname: "......",
        name: "......",
        order_num: "......",
        unit: "......",
        remark: "......",
        labels: [],
      };
      let form = {
        time: this.time,
        sort_status: this.sort_status,
        line_ids: this.line_ids,
        goods_spu_ids: this.goods_spu_ids,
        goods_id_speed: this.goods_id_speed,
        is_standard: this.is_standard,
        pid: this.pid,
        cid: this.cid,
        group_id: this.group_id,
        uids: this.uids,
        modify: this.modify,
        out_status: this.out_status,
        send_time_list: this.send_time_list,
        remark: this.remark,
        page: "1",
        pagesize: "10000000",
      };
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        form
      );
      get_goods_list(data).then((res) => {
        if (res.errcode == 0) {
          this.loading = false;
          res.data.goods_sort_speed.map((e) => {
            e.id = e.goods_id;
            let sort_speed = parseFloat(e.goods_sort_speed);
            e.sort_speed = parseFloat(sort_speed * 100).toFixed(0);
          });
          this.goods_rank = this.handleGoodsSort(res.data.goods_sort_speed);
          res.data.info.map((e) => {
            e.new_sort_num = "";
          });
          this.SORT_LIST = res.data.info;
          this.labels = res.data.labels;
          if (res.data.info.length > 0) {
            res.data.info.map((e) => {
              e.name = e.name + `【${e.spu_name}】`;
              e.labels = [];
              if (e.member && e.member.info && e.member.info.labels) {
                e.labels = e.member.info.labels;
              }
              let arr2 = [];
              let labels_ids = [];
              labels_ids = Object.keys(this.labels);
              labels_ids.filter((item) => {
                e.labels.includes(item) && arr2.push(item);
              });
              e.labels = arr2;
            });
            this.CURRENT_SORT_DATA.status = res.data.info[0].status;
            this.CURRENT_SORT_DATA = res.data.info[0];

            this.CURRENT_SELECTED = 0;
            this.$nextTick(() => {
              this.$refs.order_num_input.focus();
            });
            // this.switch_change();
          }
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },

    // 用户分拣加载
    get_user_list() {
      this.CURRENT_SORT_DATA = {
        member: {
          nickname: "......",
        },
        newname: "......",
        name: "......",
        order_num: "......",
        unit: "......",
        remark: "......",
        labels: [],
        status: "",
      };
      let form = {
        time: this.time,
        line_ids: this.user_line_ids,
        group_id: this.user_group_id,
        uids: this.user_uids,
        send_time_list: this.send_time_list,
        goods_spu_ids: this.user_goods_spu_ids,
        page: "1",
        pagesize: "10000",
        uid_zid: this.uid_zid ? this.uid_zid : "",
      };
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        form
      );
      get_user_list(data).then((res) => {
        if (res.errcode == 0) {
          this.loading = false;
          // 左侧用户列表
          let data = res.data.info;
          data.map((e) => {
            e.sort_speed = parseFloat(e.sort_speed * 100).toFixed(0);
          });
          // 右侧商品列表
          let goods_data = res.data.new_info;
          this.labels = res.data.labels;

          if (goods_data && goods_data.length > 0) {
            goods_data.map((a) => {
              a.new_sort_num = "";
              a.name = a.name + `【${a.spu_name}】`;
              a.newname = a.member.nickname;
              a.labels = [];
              if (a.member && a.member.info && a.member.info.labels) {
                a.labels = a.member.info.labels;
              }
              let arr2 = [];
              let labels_ids = [];
              labels_ids = Object.keys(this.labels);
              labels_ids.filter((item) => {
                a.labels.includes(item) && arr2.push(item);
              });
              a.labels = arr2;
            });
          }

          this.user_rank = data;
          this.SORT_LIST = goods_data;
          if (goods_data.length > 0) {
            this.user_all_data = goods_data;
            this.CURRENT_SORT_DATA = goods_data[0];
            this.CURRENT_SORT_DATA.status = goods_data[0].status;
            this.CURRENT_SELECTED = 0;
            if (this.uid_zid) {
              data.map((e) => {
                if (e.uid_zid == this.uid_zid) {
                  this.user_rank_selected = e.code;
                }
              });
            } else {
              this.user_rank_selected = data[0].code;
            }
            this.$nextTick(() => {
              this.$refs.order_num_input.focus();
            });
          } else {
            this.SORT_LIST = [];
            this.CURRENT_SORT_DATA = {
              member: {
                nickname: "......",
              },
              newname: "......",
              name: "......",
              order_num: "......",
              unit: "......",
              remark: "......",
              labels: [],
            };
          }
          // this.switch_change();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 左边用户选择
    changeUser(item) {
      this.uid_zid = item.uid_zid;
      this.user_rank_selected = item.code;
      this.get_user_list();
      this.loading = true;
    },
    // 左边商品的选择
    changeGoods(item) {
      if (item.id == this.goods_rank_selected) {
        this.goods_rank_selected = "";
      } else {
        this.goods_rank_selected = item.id;
      }
      this.goods_id_speed = this.goods_rank_selected;
      this.loading = true;
      this.get_goods_list();
    },
    // 配送日期选择
    changeDatePick(model) {
      if (model == 1) {
        // model 1  配送日期   2  配送时间
        this.$refs.child_goods.reset();
        this.$refs.child_user.reset();
        this.send_time_list = "";
        this.uids = "";
        this.user_uids = "";
        this.goods_spu_ids = "";
        this.goods_id_speed = "";
        this.goods_rank_selected = "";
        this.pid = "";
        this.cid = "";
        this.group_id = "";
        this.user_group_id = "";
        this.uid_zid = "";
      }
      let type = this.sort_type;
      this.loading = true;
      // this.time = parseTime(new Date(), "{y}-{m}-{d}");
      // this.send_time_list = "";
      this.SORT_LIST = [];
      this.CURRENT_SORT_DATA = {
        member: {
          nickname: "......",
        },
        newname: "......",
        name: "......",
        order_num: "......",
        unit: "......",
        remark: "......",
        labels: [],
      };
      switch (type) {
        case 1:
          this.get_goods_list();
          this.$refs.child_goods.updata();
          this.$refs.child_goods.get_goods_select();
          this.$refs.child_goods.get_find_user();
          break;
        case 2:
          this.get_user_list();
          this.$refs.child_user.updata();
          this.$refs.child_user.get_goods_select();
          this.$refs.child_user.get_find_user();
          break;
      }
    },
    // 商品分类选项加载
    get_goods_type() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { time: this.time }
      );
      get_goods_type(data).then((res) => {
        if (res.errcode == 0) {
          this.SEARCH_DATA = res.data;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    //切换分拣的数据
    nextGoods(item, index) {
      this.CURRENT_SELECTED = index;
      this.CURRENT_SORT_DATA = item;
      // 如果有unit_list 说明是可互调商品
      if (this.CURRENT_SORT_DATA.unit_list) {
        // 根据设置中是否可互调来设置默认选中
        this.setting_data.sorting_unit
          ? (this.sortingUnit = this.CURRENT_SORT_DATA.unit_list[0].key)
          : (this.sortingUnit = this.CURRENT_SORT_DATA.unit_list[1].key);
        if (this.CURRENT_SORT_DATA.status == 1) {
          // 如果分拣完默认选中基础单位
          this.sortingUnit = this.CURRENT_SORT_DATA.unit_list[0].key;
        }
      }
      this.$nextTick(() => {
        this.$refs.order_num_input.focus();
      });
    },
    // 数字键盘添加
    handleNumber(number) {
      if (this.CURRENT_SORT_DATA.status == 1) {
        return;
      }
      this.CURRENT_SORT_DATA.new_sort_num += String(number);
    },
    // 清除数据
    handleRemove() {
      this.CURRENT_SORT_DATA.new_sort_num = "";
    },
    // 撤销
    go_revoke() {
      let that = this;
      let sort_data = this.CURRENT_SORT_DATA;
      if (this.SORT_LIST.length == 0) {
        this.$message.warning("暂无可分拣的商品！");
        return;
      }
      if (sort_data.status == 0) {
        this.$message.warning("未分拣商品，无法撤销");
        return;
      } else {
        this.$confirm(`撤销已分拣商品,${sort_data.name}？`, "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          customClass: "quit_message",
        })
          .then(() => {
            let data = Object.assign(
              {
                sign: Md5(
                  objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
                ),
              },
              apiUrl().name,
              { id: sort_data.id }
            );
            revoke(data).then((res) => {
              if (res.errcode == 0) {
                this.$message.success("撤销成功");
                if (that.sort_type == 1) {
                  this.get_goods_list();
                } else if (that.sort_type == 2) {
                  this.get_user_list();
                }
              } else {
                this.$message.error(res.errmsg);
              }
            });
          })
          .catch(() => {});
      }
    },
    // 缺货
    go_lack() {
      let sort_data = this.CURRENT_SORT_DATA;
      if (this.SORT_LIST.length == 0) {
        this.$message.warning("暂无可分拣的商品！");
        return;
      }
      if (sort_data.status == 1) {
        this.$message.warning("该商品已经分拣");
        return;
      } else {
        this.$confirm(`是否将商品,${sort_data.name},设置为缺货？`, "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          customClass: "quit_message",
        })
          .then(() => {
            let data = Object.assign(
              {
                sign: Md5(
                  objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
                ),
              },
              apiUrl().name,
              { id: sort_data.id }
            );
            stock(data).then((res) => {
              if (res.errcode == 0) {
                this.$message.success("状态设置成功");
                this.get_goods_list();
              } else {
                this.$message.error(res.errmsg);
              }
            });
          })
          .catch(() => {});
      }
    },
    // 撤销全部
    go_lack_all() {
      let list = this.SORT_LIST;
      let arr = [];
      let length = 0;
      list.map((e) => {
        if (e.status == 1) {
          arr.push(e.id);
        }
      });
      length = arr.length;
      let ids = arr.join(",");
      if (arr.length == 0) {
        this.$message.warning("无可撤销的商品");
        return;
      }
      this.$confirm(
        `此操作将撤销已分拣的【${length}】条商品, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          customClass: "quit_message",
        }
      )
        .then(() => {
          this.loading = true;
          this.loading_text = "撤销全部中....";
          let data = Object.assign(
            {
              sign: Md5(
                objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
              ),
            },
            apiUrl().name,
            { ids: ids }
          );
          revoke_list(data).then((res) => {
            this.loading = true;
            this.loading_text = "拼命加载中....";
            if (res.errcode == 0) {
              this.$message.success("撤销成功");
              if (this.sort_type == 1) {
                this.get_goods_list();
              } else if (this.sort_type == 2) {
                this.get_user_list();
              }
            } else {
              this.$message.error("撤销失败");
            }
          });
        })
        .catch(() => {});
    },
    // 分拣全部
    go_sort_all() {
      let list = this.SORT_LIST;
      let arr = [];
      let length = 0;
      list.map((e) => {
        if (e.status == 0) {
          arr.push(e.id);
        }
      });
      length = arr.length;
      let ids = arr.join("-");
      if (arr.length == 0) {
        this.$message.warning("无可分拣的商品");
        return;
      }
      this.$confirm(`分拣未分拣的【${length}】条商品, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "quit_message",
      })
        .then(() => {
          this.loading = true;
          this.loading_text = "分拣全部中....";
          let data = Object.assign(
            {
              sign: Md5(
                objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
              ),
            },
            apiUrl().name,
            { ids: ids }
          );
          sort_list(data).then((res) => {
            this.loading = true;
            this.loading_text = "拼命加载中....";
            if (res.errcode == 0) {
              this.$message.success("全部分拣成功");
              if (this.sort_type == 1) {
                this.get_goods_list();
              } else if (this.sort_type == 2) {
                this.get_user_list();
              }
            } else {
              this.$message.error("全部分拣失败");
            }
          });
        })
        .catch(() => {});
    },
    // 添加生产日期
    add_production_time() {
      if (this.SORT_LIST.length == 0) {
        this.$message.warning("暂无可分拣的商品");
        return;
      }
      let sort_data = this.CURRENT_SORT_DATA;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          id: sort_data.id,
          mfg: sort_data.mfg,
        }
      );
      add_production_time(data).then((res) => {
        if (res.errcode != 0) {
          this.$message.error("生产日期设置失败");
          this.CURRENT_SORT_DATA.mfg = "";
        }
      });
    },
    // 添加生产数量
    add_sort_num() {
      let sort_data = this.CURRENT_SORT_DATA;
      if (this.SORT_LIST.length == 0) {
        this.$message.warning("暂无可分拣的商品");
        return;
      }
      if (!sort_data.new_sort_num) {
        this.$message.warning("请输入数量");
        return;
      } else {
        if (!/^(\d+\.?)?\d{0,4}$/.test(sort_data.new_sort_num)) {
          this.$message.error("请输入数字");
          return;
        }
        let num = Number(sort_data.new_sort_num);
        // 如果分拣的不是基础单位
        if (this.CURRENT_SORT_DATA.unit_list && this.sortingUnit == 1) {
          let info = this.CURRENT_SORT_DATA.unit_list.find(
            (item) => item.key == this.sortingUnit
          );
          let package_num = info.package_num; // 互调数量
          num = parseFloat((sort_data.new_sort_num * Number(package_num)).toFixed(2))
          sort_data.new_sort_num = num
          this.sortingUnit = 0;
        }
        let id = sort_data.id;
        let data = Object.assign(
          {
            sign: Md5(
              objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
            ),
          },
          apiUrl().name,
          {
            id: id,
            num: num,
          }
        );
        add_sort_num(data).then(async (res) => {
          if (res.errcode == 0) {
            this.$message.success("分拣数量添加成功");
            if (this.setting_data.auto_printing) {
              await this.print(id);
            }
            this.SORT_LIST[this.CURRENT_SELECTED].status = 1;
            this.SORT_LIST[this.CURRENT_SELECTED].sort_num = num.toFixed(2);
            if (this.sort_type == 1) {
              this.SORT_LIST = this.handleSortList();
              this.CURRENT_SORT_DATA = this.SORT_LIST[0];
              this.CURRENT_SELECTED = 0;
              let data = JSON.parse(JSON.stringify(this.SORT_LIST));
              let newdata = this.calculatePercent_goods(data);
              this.goods_rank.map((e) => {
                newdata.map((p) => {
                  if (e.id == p.goods_id) {
                    e.sort_speed = p.sort_speed;
                  }
                });
              });
              this.goods_rank.map((i) => {
                i.sort_num = 0;
                i.no_sort_num = i.total_sort_num;
                this.SORT_LIST.forEach((item) => {
                  if (i.id == item.goods_id && item.sort_num != "0.00") {
                    i.sort_num = Number(
                      Number(i.sort_num) +
                        Number(Number(item.sort_num).toFixed(2))
                    ).toFixed(2);
                    i.no_sort_num = Number(
                      (
                        i.no_sort_num - Number(item.sort_num).toFixed(2)
                      ).toFixed(2)
                    );
                  }
                });
              });
              this.goods_rank = this.handleGoodsSort(this.goods_rank);
            } else if (this.sort_type == 2) {
              this.SORT_LIST = this.handleSortList();
              this.CURRENT_SORT_DATA = this.SORT_LIST[0];
              this.CURRENT_SELECTED = 0;
              this.user_rank.map((e) => {
                if (e.code == this.user_rank_selected) {
                  e.sort_speed = this.calculatePercent();
                }
              });

              this.user_rank.map((i) => {
                i.sort_num1 = 0;
                this.SORT_LIST.forEach((item) => {
                  if (i.user_name == item.newname && item.status == 1) {
                    i.sort_num1 = Number(i.sort_num1) + 1;
                    i.no_sort_num = Number(
                      Number(i.total_sort_num) - Number(i.sort_num1)
                    );
                    i.sort_num = i.sort_num1;
                  }
                });
              });
            }
            this.$nextTick(() => {
              this.$refs.order_num_input.focus();
            });
          } else {
            this.$confirm(`${res.errmsg}，是否保存?`, "提示", {
              type: "warning",
            })
              .then(() => {
                this.new_add(sort_data);
              })
              .catch(() => {});
          }
        });
      }
    },
    //新分拣
    new_add(sort_data) {
      let num = Number(sort_data.new_sort_num);
      let id = sort_data.id;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          id: id,
          num: num,
          status: 1,
        }
      );
      add_sort_num(data).then((res) => {
        if (res.errcode == 0) {
          this.$message.success("分拣数量添加成功");
          if (this.setting_data.auto_printing) {
            this.print(id);
          }
          this.SORT_LIST[this.CURRENT_SELECTED].status = 1;
          this.SORT_LIST[this.CURRENT_SELECTED].sort_num = num.toFixed(2);
          if (this.sort_type == 1) {
            this.SORT_LIST = this.handleSortList();
            this.CURRENT_SORT_DATA = this.SORT_LIST[0];
            this.CURRENT_SELECTED = 0;
            let data = JSON.parse(JSON.stringify(this.SORT_LIST));
            let newdata = this.calculatePercent_goods(data);
            this.goods_rank.map((e) => {
              newdata.map((p) => {
                if (e.id == p.goods_id) {
                  e.sort_speed = p.sort_speed;
                }
              });
            });
            this.goods_rank = this.handleGoodsSort(this.goods_rank);
          } else if (this.sort_type == 2) {
            this.SORT_LIST = this.handleSortList();
            this.CURRENT_SORT_DATA = this.SORT_LIST[0];
            this.CURRENT_SELECTED = 0;
            this.user_rank.map((e) => {
              if (e.code == this.user_rank_selected) {
                e.sort_speed = this.calculatePercent();
              }
            });
          }
          this.$nextTick(() => {
            this.$refs.order_num_input.focus();
          });
        }
      });
    },
    // 商品分拣后排序
    handleSortList() {
      function compare(property) {
        return function (a, b) {
          var value1 = a[property];
          var value2 = b[property];
          return value1 - value2;
        };
      }
      this.SORT_LIST.map((e) => {
        e.sort_speed = 0;
      });
      return this.SORT_LIST.sort(compare("status"));
    },

    // 用户分拣计算已分拣百分比
    calculatePercent() {
      var all = 0;
      var is_sort = 0;
      var no_sort = 0;
      var percent = 0;
      all = this.SORT_LIST.length;
      this.SORT_LIST.map((e) => {
        if (e.status == 1) {
          is_sort++;
        } else if (e.status == 0) {
          no_sort++;
        }
      });
      if (all) {
        let cc = is_sort / all;
        percent = parseFloat(cc * 100).toFixed(0);
      }
      return percent;
    },
    // 商品分拣计算百分比
    calculatePercent_goods(data) {
      let obj = {};
      data.forEach((item, index) => {
        let { goods_id } = item;
        if (!obj[goods_id]) {
          obj[goods_id] = {
            goods_id,
            children: [],
          };
        }
        obj[goods_id].children.push(item);
      });
      let newdata = Object.values(obj);
      newdata.map((e) => {
        var all = 0;
        var is_sort = 0;
        var percent = 0;
        all = e.children.length;
        e.children.map((e) => {
          if (e.status == 1) {
            is_sort++;
          }
        });
        if (all) {
          let cc = is_sort / all;
          percent = parseFloat(cc * 100).toFixed(0);
        }
        e.sort_speed = percent;
      });
      return newdata;
    },
    // 商品分拣进度排序处理
    handleGoodsSort(data) {
      let is_sort = [];
      let no_sort = [];
      data.map((e) => {
        if (Number(e.sort_speed) == 100) {
          is_sort.push(e);
        } else {
          no_sort.push(e);
        }
      });
      no_sort.sort((a, b) => {
        a = Number(a.sort_speed);
        b = Number(b.sort_speed);
        if (a > b) {
          return -1;
        } else {
          return 1;
        }
      });
      return no_sort.concat(is_sort);
    },
    // 加载搜索的内容
    basicquerySearchAsync(queryString, cb) {
      let name = queryString;
      let type = this.quick_select_type;
      switch (type) {
        case "1":
          this.get_goods_select(name)
            .then((res) => {
              var result = res.data;
              cb(result);
            })
            .catch((res) => {
              cb([]);
            });
          break;
        case "2":
          this.get_find_user(name)
            .then((res) => {
              var result = res.data;
              result.map((e) => {
                e.name = e.nickname;
              });
              cb(result);
            })
            .catch((res) => {
              cb([]);
            });
          break;
      }
    },
    // 查找用户
    get_find_user(name) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          name: name,
          time: this.time,
        }
      );
      return new Promise((resolve, reject) => {
        get_find_user(data).then((res) => {
          if (res.errcode == 0) {
            resolve(res);
          } else {
            reject(res);
          }
        });
      });
    },
    // 查找商品
    get_goods_select(name) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          name: name,
          time: this.time,
        }
      );
      return new Promise((resolve, reject) => {
        get_goods_select(data).then((res) => {
          if (res.errcode == 0) {
            resolve(res);
          } else {
            reject(res);
          }
        });
      });
    },
    // 商品用户搜索切换
    changeQuickSelectType() {
      let type = this.quick_select_type;
      switch (type) {
        case "1":
          this.quick_select_placeholder = "商品/助记码/编码";
          break;
        case "2":
          this.quick_select_placeholder = "搜索用户";
          break;
      }
    },
    handleSelect(item) {
      let type = this.sort_type;
      this.loading = true;
      switch (type) {
        case 1:
          if (this.quick_select_type == 1) {
            this.goods_spu_ids = item.id;
          } else if (this.quick_select_type == 2) {
            this.uids = item.id;
          }
          this.get_goods_list();
          break;

        case 2:
          if (this.quick_select_type == 1) {
            this.user_goods_spu_ids = item.id;
          } else if (this.quick_select_type == 2) {
            this.user_uids = item.id;
          }
          this.get_user_list();
          break;
      }
    },
    handleClear() {
      let type = this.sort_type;
      this.loading = true;
      switch (type) {
        case 1:
          if (this.quick_select_type == 1) {
            this.goods_spu_ids = "";
          } else if (this.quick_select_type == 2) {
            this.uids = "";
          }
          this.get_goods_list();
          break;

        case 2:
          if (this.quick_select_type == 1) {
            this.user_goods_spu_ids = "";
          } else if (this.quick_select_type == 2) {
            this.user_uids = "";
          }
          this.get_user_list();
          break;
      }
    },
    // 累加事件
    go_add() {
      if (this.SORT_LIST.length == 0) {
        this.$message.warning("暂无可分拣的商品");
        return;
      } else {
        let res = this.CURRENT_SORT_DATA;
        this.addInfo.id = res.id;
        this.addInfo.num = res.sort_num;
        this.addInfo.order_num = res.order_num;
        this.addInfo.sum = 0;
        this.addInfo.sort_num = res.sort_num;
        this.addInfo.add_sum = 0;
        this.addInfo.numhistory = [];
        this.addDialogFormVisible = true;
        this.$nextTick(() => {
          this.$refs["addInfoInput"].focus();
        });
      }
    },
    // 累加回车
    countadd(value) {
      if (this.addInfo.new_num == "") {
        return;
      }
      this.addInfo.num =
        parseFloat(this.addInfo.num) + parseFloat(this.addInfo.new_num);
      this.addInfo.numhistory.push(this.addInfo.new_num);
      if (this.isPrint) {
        this.print(this.addInfo.id, this.addInfo.new_num);
      }
      if (this.addInfo.new_num) {
        this.addInfo.add_sum += parseFloat(this.addInfo.new_num);
      }

      this.addInfo.new_num = "";
    },
    close() {
      let num = this.addInfo.add_sum;
      let id = this.addInfo.id;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          id: id,
          num: num,
        }
      );
      sort_num_accumulation(data).then((res) => {
        if (res.errcode == 0) {
          this.$message.success("分拣数量累加成功");
          this.addDialogFormVisible = false;
          if (this.sort_type == 1) {
            this.get_goods_list();
          } else if (this.sort_type == 2) {
            this.get_user_list();
          }
        } else {
          this.$message.error("分拣数量添加失败");
        }
      });
    },
    // 打印
    //TODO
    print(id, num) {
      return new Promise((resolve, reject) => {
        this.$refs.printTemplate.$emit("sortPrintNote", {
          data: {
            id: id,
            num: num,
          },
          cb: (res) => {
            resolve(res);
          },
        });
      });
    },
    //打印
    go_print() {
      if (this.SORT_LIST.length == 0) {
        this.$message.warning("暂无可分拣的商品！");
        return;
      }
      let data = this.CURRENT_SORT_DATA;
      if (!this.setting_data.no_sort_printing && data.status == 0) {
        this.$message.warning("你已将未分拣打印关闭");
        return;
      }
      let id = data.id;
      this.print(id);
    },
    // 打印全部
    go_print_all() {
      let list = this.SORT_LIST;
      let arr = [];
      let length = 0;
      list.map((e) => {
        if (this.setting_data.no_sort_printing) {
          arr.push(e.id);
        } else {
          if (e.status == 1) {
            arr.push(e.id);
          }
        }
      });
      length = arr.length;
      if (length == 0) {
        this.$message.warning("暂无可打印的商品信息");
        return;
      } else {
        this.$confirm(
          `此操作将连续打印【${length}】条商品, 是否继续?`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            customClass: "quit_message",
          }
        )
          .then(async () => {
            //   TODO
            for (let index = 0; index < arr.length; index++) {
              const item = arr[index];
              await this.print(item);
            }
          })
          .catch(() => {});
      }
    },

    switch_change() {
      let that = this;

      if (this.setting_data.switch == 1) {
        init.onopen = function () {
          that.$message.success("连接成功");
          print.EB_Init(100);
        };
        init.onclose = function () {
          that.$message.error("中崎智能称连接关闭");
        };
        init.onerror = function () {
          that.$message.error("连接失败");
        };

        init.Callback = function (result) {
          let obj = JSON.parse(JSON.stringify(result));
          if (obj.name === "EB_Init") {
            if (obj.result == 0) {
              let objweight = JSON.parse(JSON.stringify(obj.data));
              if (objweight.status == 0) {
                let num_as = parseFloat(objweight.weight);
                if (num_as != 0) {
                  let a = num_as * 2;
                  let num = a.toString();
                  let num_s = num.indexOf(".");
                  let numstrend = num.slice(num_s + 1, num.length);
                  let num3 = numstrend.slice(2, 3);
                  if (num3 >= 5) {
                    let a = numstrend.slice(0, 2);
                    let b = parseInt(a) + 1;
                    let c = num.slice(0, num_s);
                    let d = `${c}.${b}`;
                    if (that.CURRENT_SORT_DATA.status == 0) {
                      that.CURRENT_SORT_DATA.new_sort_num = d;
                    }
                  } else {
                    let a_as = a.toFixed(2);
                    if (that.CURRENT_SORT_DATA.status == 0) {
                      that.CURRENT_SORT_DATA.new_sort_num = a_as;
                    }
                  }
                }
              }
            }
          }
        };
        print.webSocketConnect("ws://127.0.0.1:6363");
      }
    },
    // 按基础单位分拣
    setSortingunit() {
      // 如果有值才复制
      if(this.CURRENT_SORT_DATA.unit_list){
        // 修改下拉框选择值
        this.setting_data.sorting_unit
          ? (this.sortingUnit = this.CURRENT_SORT_DATA.unit_list[0].key)
          : (this.sortingUnit = this.CURRENT_SORT_DATA.unit_list[1].key);
      }
      if (this.CURRENT_SORT_DATA.status == 1 && this.CURRENT_SORT_DATA.unit_list) {
        // 如果分拣完成默认选中基础单位
        this.sortingUnit = this.CURRENT_SORT_DATA.unit_list[0].key;
      }
      this.$message.success("设置成功");
      localStorage.setItem("sortingUnit", this.setting_data.sorting_unit);
    },
  },
  mounted() {
    this.setting_data = {
      auto_printing: this.setting.auto_printing ? true : false,
      data_manufacture: this.setting.data_manufacture ? true : false,
      no_sort_printing: this.setting.no_sort_printing ? true : false,
      temporary_code: this.setting.temporary_code ? true : false,
      switch: this.setting.switch ? true : false,
      is_show_several: this.setting.is_show_several,
    };
    let flag = localStorage.getItem("sortingUnit") == "false" ? false : true;
    console.log(flag);
    this.$set(this.setting_data, "sorting_unit", flag);
    if (this.setting.switch == 1) {
      this.switch_change();
    }
  },

  created() {
    this.loading = true;
    this.get_goods_list();
    this.get_goods_type();
    if (this.setting.sort_info.subject_arr) {
      this.work_show = true;
      this.seting_name = this.setting.sort_info.type_second;
      this.work_ids = this.setting.sort_info.second_type.second_type;
      this.work_type = this.setting.sort_info.type_second;
      let arr = this.setting.sort_info.subject_arr.sort_subject.split(",");
      for (let i = 0; i < arr.length; i++) {
        for (let k in this.setting.sort_info.subject) {
          if (arr[i] == k) {
            this.sort_work.push(this.setting.sort_info.subject[k]);
          }
        }
      }
    }
  },
};
</script>

<style>
@import "./modify.css";
</style>

<style lang="scss" scoped>
@import "./index.scss";
</style>
